package com.ruoyi.web.controller.admin.document;


import cn.hutool.core.thread.ThreadUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.admin.domain.LlmDocuments;
import com.ruoyi.admin.service.document.ILlmDocumentsService;
import com.ruoyi.common.config.AiBaseInfoConfig;
import com.ruoyi.common.constant.MilvusConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


/**
 * 知识库上传文件控制器
 */

@Slf4j
@RestController
@RequestMapping("/document")
@RequiredArgsConstructor
public class LlmDocumentController extends BaseController {


    private final ILlmDocumentsService iLlmDocumentsService;

    @GetMapping("/index")
    public TableDataInfo index(@RequestParam("folderId") String folderId,
                               @RequestParam(name = "keyword", defaultValue = "") String keyword) {
        startPage();
        return getDataTable(iLlmDocumentsService.getList(folderId, keyword));
    }

    /**
     * 文件解析接口(此接口用于文本解析展示使用，最后会返回解析的文本结果)
     *
     * @param fileId 文件
     * @return 结果
     */
    @GetMapping("/parseFile")
    public AjaxResult parseFile(@RequestParam("fileId") String fileId,
                                @RequestParam(name = "parse", defaultValue = "1") String parse) throws Exception {
        return AjaxResult.success(iLlmDocumentsService.parseText(fileId, parse));
    }

    /**
     * @param jsonObject 前端传输对象
     * @return 异步结果
     */
    @PostMapping("/processText")
    public AjaxResult processText(@RequestBody JSONObject jsonObject) {

        String fileId = jsonObject.getString("fileId") == null ? "" : jsonObject.getString("fileId");
        String labelData = jsonObject.getString("labelData") == null ? "" : jsonObject.getString("labelData");
        String treeId = jsonObject.getString("treeId") == null ? "" : jsonObject.getString("treeId");
        String summer = jsonObject.getString("summer") == null ? "" : jsonObject.getString("summer");
        String tag = jsonObject.getString("tag") == null ? "" : jsonObject.getString("tag");
        String datasetCode = jsonObject.getString("datasetCode") == null ? "" : jsonObject.getString("datasetCode");
        String knowledgeName = jsonObject.getString("knowledgeName") == null ? "" : jsonObject.getString("knowledgeName");
        int titleRow = jsonObject.getIntValue("titleRow");
        String catalogue = jsonObject.getString("catalogue") == null ? "" : jsonObject.getString("catalogue");
        boolean b = iLlmDocumentsService.processText(fileId, labelData, treeId, summer, tag, knowledgeName, datasetCode, titleRow, catalogue);

        System.out.println("baseConfig" + AiBaseInfoConfig.getMinerUUrl());
        ThreadUtil.execAsync(() -> {
            try {
                iLlmDocumentsService.startProcessorQueue();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        return b ? AjaxResult.success() : AjaxResult.error();
    }


    /**
     * 删除文档
     *
     * @return 结果
     */
    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam("documentId") String documentId,
                             @RequestParam("datasetCode") String datasetCode) {

        return iLlmDocumentsService.deleteDocumentsReal(MilvusConstants.VECTOR_DOCUMENT_SEGMENT, datasetCode, documentId) ? AjaxResult.success() : AjaxResult.error();
    }


    /**
     * 批量删除文档
     *
     * @param jsonObject 文档id
     * @return ajax
     */
    @PostMapping("/batchDelete")
    public AjaxResult batchDelete(@RequestBody JSONObject jsonObject) {
        List<String> ids = jsonObject.getList("documentIds", String.class);
        iLlmDocumentsService.batchDeleteDocumentsReal(MilvusConstants.VECTOR_DOCUMENT_SEGMENT, jsonObject.getString("datasetCode"), ids);
        return AjaxResult.success("删除成功");
    }

    /**
     * 根据id查询处理状态
     *
     * @param jsonObject ids array
     * @return 结果
     */
    @PostMapping("/getDocumentStatus")
    public AjaxResult getDocumentStatus(@RequestBody JSONObject jsonObject) throws RuntimeException {


        JSONArray ids = jsonObject.getJSONArray("ids");
        if (ids == null) {
            return AjaxResult.success();
        }
        List<String> list = ids.toList(String.class);
        List<Map<String, Object>> documentStatus = iLlmDocumentsService.getDocumentStatus(list);

        return AjaxResult.success(documentStatus);
    }

    /**
     * 通过文档id 获取文档详细信息
     *
     * @param documentId 文档id
     * @return ajax
     */
    @GetMapping("detail")
    public AjaxResult detail(@RequestParam(name = "documentId") String documentId) {
        return AjaxResult.success(iLlmDocumentsService.getDocumentById(documentId));
    }

    /**
     * 修改文档启用状态
     *
     * @param documentId 文档id
     * @param enable     是否启用
     * @return ajax
     */
    @PutMapping("/editEnable")
    public AjaxResult editEnable(@RequestParam(name = "documentId") String documentId, @RequestParam(name = "enable") String enable) {
        return iLlmDocumentsService.editEnable(documentId, enable) ? AjaxResult.success() : AjaxResult.error();
    }


    /**
     * 修改基础信息
     *
     * @param documents 文档信息
     * @return ajax
     */
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody LlmDocuments documents) {
        return iLlmDocumentsService.editInfo(documents) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 人工切片修改原文和向量数据
     *
     * @param documents 文档信息
     * @return ajax
     */
    @PutMapping("/editDocument")
    public AjaxResult editDocument(@RequestBody LlmDocuments documents) {
        return iLlmDocumentsService.editDocument(documents) ? AjaxResult.success() : AjaxResult.error();
    }
}
